import { Card as SemiCard, ButtonGroup, Button, List } from "@douyinfe/semi-ui";
import { IconRefresh, IconDelete, IconPlusCircle, IconEdit } from "@douyinfe/semi-icons";
import { useEffect } from "react";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import OrgTree from "react-org-tree";
import { Card, message, Row, Col, Spin, Space, Modal, Radio, Popconfirm } from "antd";

import useStore from "../../hooks/store/useStore";
import useStoreDepartmentToTree from "../../hooks/store/useStoreDepartmentToTree";
import useDeleteDepartment from "../../hooks/department/useDeleteDepartment";
import useInstitutionDeletePosition from "../../hooks/institution/useDeletePosition";

import TreeStoreItem from "../tree/Store";
import TreeDepartmentItem from "../tree/Department";
import TreePersonItem from "../tree/Person";

import AddStorePerson from "./AddPosition";
import AddStoreDepartment from "./AddDepartment";
import AddStoreDepartmentPosition from "./AddDepartmentPosition";

import EditStoreDepartment from "./EditDepartment";

const StoreTree = ({ oiType, oiUuid, cardBodyHeight }) => {
    const { loadStore } = useStore();
    const { loadStoreDepartmentsToTree } = useStoreDepartmentToTree();
    const { deleteDepartment } = useDeleteDepartment();
    const { deleteInstitutionPosition } = useInstitutionDeletePosition();

    const state = useReactive({
        loading: false,
        selectStore: {},
        horizontal: false,
    });

    const loadDepartments = async () => {
        let store = await loadStore(oiUuid);

        if (!store) return;

        state.loading = true;
        state.isShowTree = false;

        let defaultNode = {
            id: 0,
            oiUuid: store.oiUuid,
            oiName: store.oiName,
            type: "store",
            maInfo: store.maInfo,
        };

        let departments = await loadStoreDepartmentsToTree({ oiType: "门店部门", oiRoot: store.oiUuid });
        let groups = await loadStoreDepartmentsToTree({ oiType: "门店班组", oiRoot: store.oiUuid });

        let children = store.children;

        if (departments.length > 0) children = children.concat(departments);
        if (groups.length > 0) children = children.concat(groups);

        state.treeData = { ...defaultNode, children };

        if (!state.selectNode) {
            state.selectNode = defaultNode;
        } else {
            if (state.selectNode.type === "department") {
                let department = children.find((item) => item.oiUuid === state.selectNode.oiUuid);
                department && (state.selectNode = { ...department, type: "department", id: department.oiUuid });
            }
        }
        // if (departments.length === 0) {
        //     state.treeData = { ...defaultNode, children: store.children || [] };
        //     state.selectNode = defaultNode;
        //     state.loading = false;
        //     state.isShowTree = true;
        //     return;
        // } else {
        //     let children = store.children ? store.children.concat(departments.concat(groups)) : departments.concat(groups);
        //     state.treeData = { ...defaultNode, children };
        //     if (!state.selectNode) {
        //         state.selectNode = defaultNode;
        //     } else {
        //         if (state.selectNode.type === "department") {
        //             let department = departments.find((item) => item.oiUuid === state.selectNode.oiUuid);
        //             department && (state.selectNode = { ...department, type: "department", id: department.oiUuid });
        //         }
        //     }
        // }

        state.loading = false;
        state.isShowTree = true;
    };

    useEffect(() => {
        loadDepartments();
    }, [oiUuid]);

    const deleteNode = async () => {
        if (!state.selectNode?.oiUuid) return;
        const { type } = state.selectNode;
        if (type === "department") {
            await deleteDepartment(state.selectNode.oiUuid, async () => {
                state.selectNode = null;
                loadDepartments();
            });
        } else if (type === "person") {
            let res = await deleteInstitutionPosition(state.selectNode.reUuid);
            if (res) {
                message.success("成功移除部门职位人员");
                state.selectNode = null;
                s;
                loadDepartments();
            }
        }
    };

    const renderContent = (data) => {
        let content = "";
        switch (data.type) {
            case "store":
                content = <TreeStoreItem key={data.id} data={data} selectNode={state.selectNode} />;
                break;
            case "department":
                content = <TreeDepartmentItem key={data.id} data={data} selectNode={state.selectNode} />;
                break;
            case "person":
                content = <TreePersonItem key={data.id} data={data} selectNode={state.selectNode} />;
                break;
            default:
                break;
        }
        return content;
    };

    const cardTitle = (
        <span style={{ lineHeight: "32px", fontSize: 15 }}>
            {state.selectNode?.oiName || state.selectNode?.odName || state.selectNode?.staff.osName || state.selectNode?.member.omName || "-"}{" "}
        </span>
    );

    return (
        <Row gutter={10}>
            <Col span={17}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 15 }}>{oiType}架构</span>}
                    headerStyle={{ padding: "7px 12px" }}
                    headerExtraContent={
                        <Space>
                            <Radio.Group
                                options={[
                                    { label: "竖向", value: false },
                                    { label: "横向", value: true },
                                ]}
                                onChange={({ target: { value } }) => (state.horizontal = value)}
                                value={state.horizontal}
                                optionType="button"
                                buttonStyle="solid"
                            />
                            <Button icon={<IconRefresh />} onClick={loadDepartments}></Button>
                        </Space>
                    }
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight, overflow: "auto", textAlign: "center" }}
                >
                    <Spin spinning={state.loading}>
                        {state.isShowTree && (
                            <OrgTree
                                horizontal={state.horizontal}
                                data={state.treeData}
                                collapsable={true}
                                labelClassName={"org-tree-label"}
                                expandAll={true}
                                renderContent={renderContent}
                                onClick={(e, data) => (state.selectNode = data)}
                            />
                        )}
                    </Spin>
                </SemiCard>
            </Col>
            <Col span={7}>
                <SemiCard
                    title={cardTitle}
                    headerStyle={{ padding: "7px 12px" }}
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight }}
                    headerExtraContent={
                        <ButtonGroup>
                            {state.selectNode && state.selectNode.id !== 0 && (
                                <Popconfirm title={`确认要删除该${state.selectNode.type === "person" ? "岗位" : "部门"}信息吗？`} onConfirm={deleteNode}>
                                    <Button icon={<IconDelete style={{ color: "#E91E63" }} />}></Button>
                                </Popconfirm>
                            )}
                        </ButtonGroup>
                    }
                >
                    <Space direction="vertical" size={10} style={{ padding: "10px 16px", width: "100%" }}>
                        {state.selectNode?.type === "store" && (
                            <Card title="添加门店机构" bordered={true} size="small">
                                <AddStoreDepartment oiUuid={oiUuid} reloadData={loadDepartments} />
                            </Card>
                        )}

                        {state.selectNode?.type === "store" && (
                            <Card title="添加岗位（员工）" bordered={true} size="small">
                                <AddStorePerson oiUuid={oiUuid} reloadData={loadDepartments} />
                            </Card>
                        )}

                        {state.selectNode?.type === "department" && (
                            <Card title="编辑门店机构信息" bordered={true} size="small">
                                <EditStoreDepartment department={state.selectNode} reloadData={loadDepartments} />
                            </Card>
                        )}

                        {state.selectNode?.type === "department" && (
                            <Card title="添加岗位（员工）" bordered={true} size="small">
                                <AddStoreDepartmentPosition department={state.selectNode} reloadData={loadDepartments} />
                            </Card>
                        )}
                    </Space>
                </SemiCard>
            </Col>
        </Row>
    );
};

export default StoreTree;
